

class EmployeeController extends BaseController{
    def beforeInterceptor = [action:this.auth]
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        def access = session.access
        access.refresh()
        def listEmpl = access.getList("employee")
        [ employeeInstanceList:listEmpl , employeeInstanceTotal: listEmpl.count()]
    }

    def show = {
        def employeeInstance = DBConnection.getEmployee( params.id )
        
        if(!employeeInstance) {
            flash.message = "Employee not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            ArrayList a = employeeInstance.listOfProjects()                            //A list of whoas for this year
            Integer actualHours = employeeInstance.actualWorkingHoursPerYear()         //Can skip this and use employeeInstance.actualWorkingHoursPerYear() instead

            if(ModeAccess.isAvailableInCurrentMode(session.mode,employeeInstance.mode)){
                // If the employee mode corresponds to the current mode
                return [ employeeInstance : employeeInstance, whoaList : a, actualHours : actualHours]
            }
            else{
                flash.message = "Employee not accessible in current mode"
                redirect(action:list)
            }
        }
    }

    def delete = {
        def employeeInstance = DBConnection.getEmployee( params.id )
        if(employeeInstance) {
            try {
                DBConnection.deleteEmployee(employeeInstance.id)
                session.modified = true //to show popup window
                flash.message = "Employee ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Employee ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Employee not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def employeeInstance = DBConnection.getEmployee( params.id )

        if(!employeeInstance) {
            flash.message = "Employee not found with id ${params.id}"
            redirect(action:list)
        }
        else {
             if(ModeAccess.isAvailableInCurrentMode(session.mode,employeeInstance.mode)){
                // If the employee mode corresponds to the current mode
               return [ employeeInstance : employeeInstance, areas : session.access.getList("area") ]

            }
            else{
                flash.message = "Employee not accessible in current mode"
                redirect(action:list)
            }
            
        }
    }

    def update = {

        //Check that date of birth is correct
        if(params.dob_month.equals("4")||params.dob_month.equals("6")||params.dob_month.equals("9")||params.dob_month.equals("11")){
            if(params.dob_day.equals("31")){
                    params.dob_month = "ab"
            }
        }

        if(params.dob_month.equals("2")){ // check february month
            if(params.dob_day.equals("31")||params.dob_day.equals("30")){
                    params.dob_month = "ab"
            }
        }
        
        def employeeInstance = DBConnection.getEmployee( params.id )

        if(employeeInstance) {
            if(DBConnection.isConnectionStarted()){
                employeeInstance.properties = params
                if(!employeeInstance.hasErrors()) {
                    //from here own constraints
                    Integer wrong=0
                  //firstName

                    if(!employeeInstance.firstName){
                      employeeInstance.errors.rejectValue("firstName","employee.firstname.is.empty", "The First Name should be specified.")
                       wrong=1
                    }

                    else{ if(!(employeeInstance.firstName.matches("[a-öA-Ö ]+"))){//Ö
                     employeeInstance.errors.rejectValue("firstName","employee.firstname.is.wrong", "The First Name should only include characters from a-ö.")
                      wrong=1}}
                       //lastName
                   
                    if(!employeeInstance.lastName){
                        employeeInstance.errors.rejectValue("lastName" ,"employee.lastname.is.empty", "The Last Name should be specified.")
                         wrong=1
                    }
                     else{

                     if(!(employeeInstance.lastName.matches("[a-öA-Ö ]+"))){//Ö  employeeInstance.firstName =~ /[a-öA-Ö ]/
                      employeeInstance.errors.rejectValue("lastName","employee.lastName.is.wrong", "The Last Name should only include characters from a-ö.")
                  wrong=1
                    }
                    }

                   if(!employeeInstance.street){
                        employeeInstance.errors.rejectValue( "street","employee.street.is.empty", "The Street should be specified.")
                       wrong=1
                    }
                   else{
                       if(!employeeInstance.street.matches("[a-öA-Ö0-9 ]+")){//Ö
                      employeeInstance.errors.rejectValue("street","employee.street.is.wrong", "The Street should only include characters from a-ö.")
                         wrong=1
                    }
                }


                      if(!employeeInstance.city){
                        employeeInstance.errors.rejectValue( "city","employee.city.is.empty", "The City should be specified.")
                        wrong=1
                    }
                     else{
                       if(!employeeInstance.city.matches("[a-öA-Ö]+")){//Ö
                      employeeInstance.errors.rejectValue("city","employee.city.is.wrong", "The City should only include characters from a-ö.")
                        wrong=1
                    }}

                    if(!employeeInstance.zipCode){
                        employeeInstance.errors.rejectValue( "zipCode","employee.zipCode.is.empty", "The Zip Code should be specified.")
                         wrong=1
                    }
                    else{
                     if(employeeInstance.zipCode<10000 || employeeInstance.zipCode>99999){
                        employeeInstance.errors.rejectValue( "zipCode","employee.zipCode.is.not", "The Zip Code is not correct.")
                        wrong=1
                    }}
                if(employeeInstance.dob>new Date()){
                         employeeInstance.errors.rejectValue("dob" ,"employee.dop.is.not", "The DOB is not correct.")
                       wrong=1
                    }
                     if(!employeeInstance.email){
                         employeeInstance.errors.rejectValue("email" ,"employee.email.is.empty", "The Email should be specified.")
                       wrong=1
                    }
                    else{
                    if(!employeeInstance.email.matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}")){//Ö
                           employeeInstance.errors.rejectValue("email" ,"employee.email.wrong", "The Email is not correct.")
                       wrong=1
                    }}
                     if(!employeeInstance.title){
                        employeeInstance.errors.rejectValue( "title","employee.title.is.empty", "The Title should be specified.")
                        wrong=1
                    }

                //percentageWork
                 if(!employeeInstance.percentageWork){
                        employeeInstance.errors.rejectValue( "percentageWork","employee.percentageWork.is.empty", "Percentage Work should be specified.")
                      wrong=1
                    }
                    else{
                     if(employeeInstance.percentageWork<0 || employeeInstance.percentageWork>100){
                        employeeInstance.errors.rejectValue( "percentageWork","employee.percentageWork.is.wrong", "Percentage Work should be between 0-100 percent.")
                       wrong=1
                    }}
                   if(!employeeInstance.salary){
                        employeeInstance.errors.rejectValue( "salary","employee.salary.is.empty", "The Salary should be specified.")
                        render(view:'create',model:[employeeInstance:employeeInstance] )
                    }
                    else{
                         if(employeeInstance.salary<0d||employeeInstance.salary>999999d){
                        employeeInstance.errors.rejectValue( "salary","employee.salary.is.not", "The Salary should be between 0 and 999 999.")
                        wrong=1
                    }


                    }
                     if(!employeeInstance.phoneNumber){
                        employeeInstance.errors.rejectValue( "phoneNumber","employee.phoneNumber.is.empty", "The Phone Number should be specified.")
                       wrong=1
                    }


                    ////to here own constraints
                    if(wrong==1){
                      render(view:'edit',model:[employeeInstance:employeeInstance] )
                    }
                   else {
                  DBConnection.updateEmployee(employeeInstance)
                    session.modified = true // to show popup window
                    flash.message = "Employee ${employeeInstance} updated in sandbox"
                    redirect(action:show,id:employeeInstance.id)
                }}
                else {
                    render(view:'edit',model:[employeeInstance:employeeInstance])
                }
            }
            else{
                if(params.version) {
                    def version = params.version.toLong()
                    if(employeeInstance.version > version) {

                        employeeInstance.errors.rejectValue("version", "employee.optimistic.locking.failure", "Another user has updated this Employee while you were editing.")
                        render(view:'edit',model:[employeeInstance:employeeInstance])
                        return
                    }
                }
                employeeInstance.properties = params
                if(!employeeInstance.hasErrors() && employeeInstance.save()) {
                    flash.message = "Employee ${params.id} updated"
                    redirect(action:show,id:employeeInstance.id)
                }
                else {
                    render(view:'edit',model:[employeeInstance:employeeInstance])
                }
            }

        } //employeeinstance
        else {
            flash.message = "Employee not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def access = session.access
        access.refresh()
        if(access.checkAccess("employee", "create", null)){
            def employeeInstance = new Employee()
            employeeInstance.properties = params
            return ['employeeInstance':employeeInstance, areaList:access.getList("area")]
        }
        else{
            flash.message = "Missing privilege for this action!"
            redirect(action:list)
        }
    }

    def save = {
         //Check that date of birth is correct
        if(params.dob_month.equals("4")||params.dob_month.equals("6")||params.dob_month.equals("9")||params.dob_month.equals("11")){
            if(params.dob_day.equals("31")){
                    params.dob_month = "ab"
            }
        }

        if(params.dob_month.equals("2")){ // check february month
            if(params.dob_day.equals("31")||params.dob_day.equals("30")){
                    params.dob_month = "ab"
            }
        }

        if(params.mode.equalsIgnoreCase("budget")){
            params.mode=0
        }
        else{
            params.mode=1
        }

        def employeeInstance = new Employee(params)

        if(!employeeInstance.hasErrors()) {
            if(DBConnection.isConnectionStarted()){
            //here for constraints
                if(!employeeInstance.employeeId){
                    employeeInstance.errors.rejectValue("employeeId","employee.employeeId.is.empty", "The EmployeeId should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                if(!employeeInstance.firstName){
                    employeeInstance.errors.rejectValue("firstName","employee.firstname.is.empty", "The First Name should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                // if (!matcher.find()) {
                if(!(employeeInstance.firstName.matches("[a-öA-Ö ]+"))){//Ö
                    employeeInstance.errors.rejectValue("firstName","employee.firstname.is.wrong", "The First Name should only include characters from a-ö.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                if(!employeeInstance.lastName){
                    employeeInstance.errors.rejectValue("lastName" ,"employee.lastname.is.empty", "The Last Name should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                else{
                    if(!(employeeInstance.lastName.matches("[a-öA-Ö ]+"))){//Ö  employeeInstance.firstName =~ /[a-öA-Ö ]/
                        employeeInstance.errors.rejectValue("lastName","employee.lastName.is.wrong", "The Last Name should only include characters from a-ö.")
                        render(view:'create',model:[employeeInstance:employeeInstance] )
                    }
                }
                if(!employeeInstance.street){
                    employeeInstance.errors.rejectValue( "street","employee.street.is.empty", "The Street should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                else{
                    if(!employeeInstance.street.matches("[a-öA-Ö0-9 ]+")){//Ö
                        employeeInstance.errors.rejectValue("street","employee.street.is.wrong", "The Street should only include characters from a-ö.")
                        render(view:'create',model:[employeeInstance:employeeInstance] )
                    }
                }
                if(!employeeInstance.city){
                    employeeInstance.errors.rejectValue( "city","employee.city.is.empty", "The City should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                else{
                    if(!employeeInstance.city.matches("[a-öA-Ö]+")){//Ö
                        employeeInstance.errors.rejectValue("city","employee.city.is.wrong", "The City should only include characters from a-ö.")
                        render(view:'create',model:[employeeInstance:employeeInstance] )
                    }
                }
                if(!employeeInstance.zipCode){
                    employeeInstance.errors.rejectValue( "zipCode","employee.zipCode.is.empty", "The Zip Code should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                else{
                    if(employeeInstance.zipCode<10000 || employeeInstance.zipCode>99999){
                        employeeInstance.errors.rejectValue( "zipCode","employee.zipCode.is.not", "The Zip Code is not correct.")
                        render(view:'create',model:[employeeInstance:employeeInstance] )
                    }
                }
                if(employeeInstance.dob>new Date()){
                    employeeInstance.errors.rejectValue("dob" ,"employee.dop.is.not", "The Date Of Birth is not correct.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                if(!employeeInstance.email){
                    employeeInstance.errors.rejectValue("email" ,"employee.email.is.empty", "The Email should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                else{
                    if(!employeeInstance.email.matches("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}")){//Ö
                        employeeInstance.errors.rejectValue("email" ,"employee.email.wrong", "The Email is not correct.")
                        render(view:'create',model:[employeeInstance:employeeInstance] )
                    }
                }
                if(!employeeInstance.title){
                    employeeInstance.errors.rejectValue( "title","employee.title.is.empty", "The Title should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }

                //percentageWork
                if(!employeeInstance.percentageWork){
                    employeeInstance.errors.rejectValue( "percentageWork","employee.percentageWork.is.empty", "Percentage Work should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                else{
                    if(employeeInstance.percentageWork<0 || employeeInstance.percentageWork>100){
                        employeeInstance.errors.rejectValue( "percentageWork","employee.percentageWork.is.wrong", "Percentage Work should be between 0-100 percent.")
                        render(view:'create',model:[employeeInstance:employeeInstance] )
                    }
                }
                if(!employeeInstance.salary){
                    employeeInstance.errors.rejectValue( "salary","employee.salary.is.empty", "The Salary should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }
                else{
                    if(employeeInstance.salary<0d||employeeInstance.salary>999999d){
                        employeeInstance.errors.rejectValue( "salary","employee.salary.is.not", "The Salary should be between 0 and 999 999.")
                        render(view:'create',model:[employeeInstance:employeeInstance] )
                    }
                }
                if(!employeeInstance.phoneNumber){
                    employeeInstance.errors.rejectValue( "phoneNumber","employee.phoneNumber.is.empty", "The Phone Number should be specified.")
                    render(view:'create',model:[employeeInstance:employeeInstance] )
                }

                Integer idE
                if((idE=DBConnection.saveEmployee(employeeInstance))>0){
                    session.modified = true // to show popup window
                    flash.message = "Employee ${idE} created"
                    redirect(action:show,id:idE)
                }
                else{
                    println("idE: " + idE)
                    if(idE==-2){
                        employeeInstance.errors.rejectValue("employeeId","employee.employeeId.is.not.unique", "The EmployeeId should be unique.")
                        render(view:'create',model:[employeeInstance:employeeInstance])
                    }
                    employeeInstance.errors.rejectValue("","", "Something went wrong!")
                    render(view:'create',model:[employeeInstance:employeeInstance])
                }
            }
        }
        else{ //has errors
            if(employeeInstance.save()){
                flash.message = "Employee ${employeeInstance} created"
                redirect(action:show,id:employeeInstance.id)
            }
            else{
                render(view:'create',model:[employeeInstance:employeeInstance])
            }
        }
    }

   def updateFigures = {
        Float newFigure = Float.parseFloat(params.figure);

        def employeeInstance = DBConnection.getEmployee(params.id);   // The ID from javascript (that comes from show)
        
        if(params.type == "percentageWork"){
            /*if(newFigure<0 || newFigure>100){
                  flash.message = "Percentage is wrong"
                  redirect(action:blank)
                 }*/
            employeeInstance.percentageWork = newFigure;
        }
        else if (params.type == "hoursWork") {
           /*   if( newFigure>employeeInstance.getWorkingHoursPerYear()|| newFigure<0){
                  flash.message = "Workhours is wrong"
                  redirect(action:blank);
                 }*/
            employeeInstance.percentageWork =  employeeInstance.updateWorkPercentageWithHours(newFigure)
        }
        else if (params.type == "percentageWorkUpArrow") {
            
            employeeInstance.percentageWork = employeeInstance.arrowUp()
        }
        else if (params.type == "percentageWorkDownArrow"){
          
            employeeInstance.percentageWork = employeeInstance.arrowDown()
        }
        else{
           //  b.knownTotalIncome = newIncome;
        }
        if(DBConnection.isConnectionStarted()){
     
            DBConnection.updateEmployee(employeeInstance);
            session.modified = true // to show popup window

        }
        else{
            employeeInstance.save(flush:true);
        }
        /*
        if(employeeInstance.save(flush:true)){ // save method is an boolean
            println("saved motherfucker!");
        }
        else{
             employeeInstance.errors.each {
                  println(it);
                }
                
        }
        */

        redirect(action:blank);

    }
    def blank = {}
}
